def read_resource_file(filename):
    """
    读取资源文件内容
    参数:
        filename: 文件名
    返回:
        lines: 文件内容行列表
    """
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.readlines()
    except FileNotFoundError:
        print("错误：找不到文件", filename)
        return []


def parse_resources(lines):
    """
    解析资源数据
    参数:
        lines: 文件内容行列表
    返回:
        total_cpu: CPU核心总数
        total_memory: 内存总量(GB)
        total_disk: 磁盘总量(GB)
    """
    total_cpu = 0
    total_memory = 0
    total_disk = 0

    for line in lines:
        # 移除空白字符
        line = line.strip()
        if not line:
            continue

        # 将行按空格和制表符分割成项目
        items = line.split()

        for item in items:
            # 解析CPU信息
            if 'CPU:' in item:
                try:
                    cpu_count = int(item.split(':')[1].replace('核', ''))
                    total_cpu += cpu_count
                except (IndexError, ValueError):
                    print(f"警告：无法解析CPU信息: {item}")

            # 解析内存信息
            elif '内存:' in item:
                try:
                    memory = float(item.split(':')[1].replace('GB', ''))
                    total_memory += memory
                except (IndexError, ValueError):
                    print(f"警告：无法解析内存信息: {item}")

            # 解析磁盘信息
            elif 'GB' in item and '内存:' not in item:
                try:
                    disk = float(item.replace('GB', ''))
                    total_disk += disk
                except (IndexError, ValueError):
                    print(f"警告：无法解析磁盘信息: {item}")

    return total_cpu, total_memory, total_disk


def print_summary(cpu_count, memory_gb, disk_gb):
    """
    打印资源汇总信息
    参数:
        cpu_count: CPU核心总数
        memory_gb: 内存总量(GB)
        disk_gb: 磁盘总量(GB)
    """
    disk_tb = disk_gb / 1024  # 转换为TB
    print(f"系统资源汇总:")
    print(f"CPU总核心数: {cpu_count}C")
    print(f"内存总量: {memory_gb}G")
    print(f"磁盘总量: {disk_gb}GB")
    print(f"磁盘总量: {disk_tb:.2f}TB")  # 保留两位小数


def main():
    """
    主函数
    """
    filename = "操作系统资源.txt"
    lines = read_resource_file(filename)

    if lines:
        cpu_count, memory_gb, disk_gb = parse_resources(lines)
        print_summary(cpu_count, memory_gb, disk_gb)


if __name__ == "__main__":
    main()
